<?php
/*
 * @project CreativeFramework
 * @version <#RELEASE_VERSION#>
 * @license GNU Lesser General Public License
 * @author Jimmie Lin
 */

/************************************************
 * This file needs serious cleanup.
 */

class pagination {
	/**
	 * calculatePages
	 * Calculates number of pages with given number of items and number of items per page.
	 * @param int items
	 * @param int perPage=20
	 * @return int
	 */
	public function calculatePages($items, $perPage = 20){
		return ceil($items/$perPage);
	}
	
	/**
	 * calculateOffsetXY
	 * Calculates the offset and limit (x, y) to pass to the Database Class with given number of items and pages
	 * @param int perPage=20
	 * @param int pages=1
	 * @return array(offset, limit)
	 */
	public function calculateOffsetXY($perpage = 20, $page = 1) {
		$x = ($page-1)*$perpage;
		$y = $page*$perpage;
		return array($x, $y);
	}
	
	/**
	 * generateLinks
	 * Generates the pagination links with given baseurl, current page, and number of pages. It returns it!
	 * Note: BaseURL MUST always have a ?something=somevalue, because only &page=PAGEID will be appended. This will probably be fixed after Dev Preview
	 * @param string baseurl
	 * @param int currentpage
	 * @param int pages
	 * @return string
	 */
	public function generateLinks($baseurl, $currentpage, $pages) {
		// FIXME: There's hardcoded HTML over here! AAH! :O
		global $Smarty;
		$baseurl = WEB_PATH.$baseurl;
		$Smarty->assign("baseurl", $baseurl);
		$Smarty->assign("currentpage", $currentpage);
		$Smarty->assign("pages", $pages);
		// Smarty is slow on direct PHP so we have to generate the for loop over here
		$O = ""; 
		if($pages < 8) {
			for($i=1;($i-1)!=$pages;$i++) {
				// echo $i;
				if($i != $currentpage) $O .= "<a href='{$baseurl}&amp;page={$i}' class='pagination_link'>{$i}</a>";
				else $O .= "<a class='pagination_link pagination_link_active'>{$i}</a>";
			}
		}
		else {
			if($currentpage < 8) {
				for($i=1;($i-1)!=8;$i++) {
					// echo $i;
					if($i != $currentpage) $O .= "<a href='{$baseurl}&amp;page={$i}' class='pagination_link'>{$i}</a>";
					else $O .= "<a class='pagination_link pagination_link_active'>{$i}</a>";
				}
			}
			else{
				$mxpage = $currentpage+4;
				if($mxpage > $pages) $mxpage = $pages;
				for($i=($currentpage-3);($i-1)!=($mxpage);$i++) {
					// echo $i;
					if($i != $currentpage) $O .= "<a href='{$baseurl}&amp;page={$i}' class='pagination_link'>{$i}</a>";
					else $O .= "<a class='pagination_link pagination_link_active'>{$i}</a>";
				}
			}
			#$O .= $Smarty->fetch("pagination_more.tpl");
		}
		$Smarty->assign("data", $O);
		return $Smarty->fetch("pagination_links.tpl");
	}
}
